package com.gongyibao.gbase.common;

import com.gongyibao.gbase.utils.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author duwh
 * @ClassName: BaseController
 * @Description: 通用控制层
 * @date 2018年4月12日 上午9:41:23
 */
public abstract class BaseController {

    protected org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());

    /**
     * 解决前台form提交日期字符串，映射实体类的日期属性时格式化错误问题
     *
     * @param dataBinder
     * @author Kunpeng
     */
    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        /**
         * 解决前台form提交List过长而导致无法提交的问题
         *
         * @param binder
         * @author
         */
        dataBinder.setAutoGrowCollectionLimit(1024);
        /**
         * 预定义的日期格式
         */
        final List<String> formatPatterns = Arrays.asList("yyyy", "yyyy-MM", "yyyy-MM-dd", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS");

        dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            private Date parse(String source) {
                if (StringUtils.isBlank(source)) {
                    return null;
                }
                source = source.trim();

                Date date;

                if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}.\\d{1,3}$")) {
                    System.out.println("MyDateFormat.parse(String " + source + ") ---- " + formatPatterns.get(5));
                    date = parseDate(source, formatPatterns.get(5));
                } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
                    System.out.println("MyDateFormat.parse(String " + source + ") ---- " + formatPatterns.get(4));
                    date = parseDate(source, formatPatterns.get(4));
                } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
                    System.out.println("MyDateFormat.parse(String " + source + ") ---- " + formatPatterns.get(3));
                    date = parseDate(source, formatPatterns.get(3));
                } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
                    System.out.println("MyDateFormat.parse(String " + source + ") ---- " + formatPatterns.get(2));
                    date = parseDate(source, formatPatterns.get(2));
                } else if (source.matches("^\\d{4}-\\d{1,2}$")) {
                    System.out.println("MyDateFormat.parse(String " + source + ") ---- " + formatPatterns.get(1));
                    date = parseDate(source, formatPatterns.get(1));
                } else if (source.matches("^\\d{4}$")) {
                    System.out.println("MyDateFormat.parse(String " + source + ") ---- " + formatPatterns.get(0));
                    date = parseDate(source, formatPatterns.get(0));
                } else {
                    throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
                }

                return date;
            }

            /**
             * 格式化日期
             *
             * @param dateStr String 字符型日期
             * @param format  String 格式
             * @return Date 日期
             */
            private Date parseDate(String dateStr, String format) {
                Date date = null;
                try {
                    DateFormat dateFormat = new SimpleDateFormat(format);
                    date = dateFormat.parse(dateStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return date;
            }

            public void setAsText(String value) {
                try {
                    System.out.println("dataBinder.registerCustomEditor.setAsText(String value) " + value);
                    setValue(parse(value));
                    //setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(value));
                } catch (RuntimeException re) {
                    System.out.println("dataBinder.registerCustomEditor " + re);
                    setValue(null);
                }
            }

            public String getAsText() {
                System.out.println("dataBinder.registerCustomEditor.getAsText()");
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format((Date) getValue());
            }

        });
    }

    /**
     * 功能：通用返回方法 <br/>
     *
     * @author zhouk
     * @version 2018年11月24日 下午4:50:40 <br/>
     */
    protected static <T> BaseResult<T> success(T dataPoints) {
        return success(dataPoints, "成功");
    }

    protected static <T> BaseResult<T> success(T dataPoints, String statusMessage) {
        return new BaseResult.Builder<T>().setStatusCodeSuccess().statusMessage(statusMessage).dataPoints(dataPoints).build();
    }

    protected static BaseResult<Object> success() {
        return new BaseResult.Builder<>().setStatusCodeSuccess().statusMessage("成功").build();
    }

    protected static <T> BaseResult<T> fail(T dataPoints) {
        return fail(dataPoints, "失败");
    }

    protected static <T> BaseResult<T> fail(T dataPoints, String statusMessage) {
        return new BaseResult.Builder<T>().setStatusCodeFail().statusMessage(statusMessage).dataPoints(dataPoints).build();
    }

    protected static BaseResult<Object> fail() {
        return new BaseResult.Builder<>().setStatusCodeFail().statusMessage("失败").build();
    }


}
